﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Vivo针板ID设置软件
{
    /// <summary>
    /// Free 为空闲状态
    /// ReadID 为读ID命令
    /// ReadIDAck 为读ID应答
    /// WriteID 为写ID命令
    /// WriteIDAck 为写ID命令应答
    /// </summary>
    public enum ReadWriteStatus{Free,ReadID,ReadIDAck,WriteID,WriteIDAck};

    public partial class Form1 : Form
    {
        ReadWriteStatus PinBoardRWStatus = ReadWriteStatus.Free;
        /// <summary>
        /// 线程管理
        /// </summary>
        Dictionary<string, Thread> threadMana = new Dictionary<string, Thread>();


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] PortNames = SerialPort.GetPortNames();    //获取本机串口名称，存入PortNames数组中

            if(PortNames.Count() == 0)
            {
                MessageBox.Show("本地没有可用的串口，请检查驱动是否正确安装以及接线是否正常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //至少有一个串口号时，才会激活按键
            butSerialPortCtl.Enabled = true;

            for (int i = PortNames.Count(); i > 0; i--)
            {
                cmbSerilPort.Items.Add(PortNames[i-1]);   //将数组内容加载到comboBox控件中
            }
            cmbSerilPort.SelectedIndex = 0;

            label2.Text = "提示：软件默认波特率为" + serialPort1.BaudRate.ToString();

        }

        private void butSerialPortCtl_Click(object sender, EventArgs e)
        {
            if(serialPort1.IsOpen == false)//
            {
                try
                {
                    serialPort1.PortName = cmbSerilPort.Text;
                    serialPort1.BaudRate = Convert.ToInt32(tb_Bauds.Text.Trim());
                    label2.Text = "提示：软件当前串口波特率为" + serialPort1.BaudRate.ToString();
                    serialPort1.Open();
                    cmbSerilPort.Enabled = false;
                    tb_Bauds.Enabled = false;
                    butSerialPortCtl.Text = "关闭串口";
                    buttonCtl(true);
                }
                catch {
                    MessageBox.Show("端口异常，请关闭软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                
            }
            else if(serialPort1.IsOpen == true)
            {
                try
                {
                    serialPort1.Close();
                    cmbSerilPort.Enabled = true;
                    tb_Bauds.Enabled = true;
                    butSerialPortCtl.Text = "打开串口";
                    buttonCtl(false);
                }
                catch
                {
                    MessageBox.Show("端口异常，请关闭软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string idstr = tbPinBoardID.Text;

            if(idstr.Length > 30)
            {
                MessageBox.Show("针板ID只支持1-30个字符！现在为" + idstr.Length.ToString() + "个字符！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (idstr.Length == 0)
            {
                MessageBox.Show("针板ID不能为空，请输入针板ID！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string cmdstr = "WID_" + idstr + "\r\n";
            serialPort1.Write(cmdstr);

            Thread th = new Thread(SerialPortReadThread);
            th.IsBackground = true;
            th.Name = "ReadThread";
            threadMana.Add(th.Name, th);
            th.Start();

            PinBoardRWStatus = ReadWriteStatus.WriteIDAck;
            timer1.Interval = 800;
            timer1.Enabled = true;
            buttonCtl(false);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            char[] cmd = {'R','I','D','\r','\n' };
            serialPort1.Write(cmd, 0, 5);


            Thread th = new Thread(SerialPortReadThread);
            th.IsBackground = true;
            th.Name = "ReadThread";
            threadMana.Add(th.Name, th);
            th.Start();

            PinBoardRWStatus = ReadWriteStatus.ReadIDAck;
            timer1.Interval = 800;
            timer1.Enabled = true;
            buttonCtl(false);
        }

        private void buttonCtl(bool enbaled)
        {
            button2.Enabled = enbaled;
            button3.Enabled = enbaled;
            
        }

        private void SerialPortReadThread()
        {
            string datastr = serialPort1.ReadLine();
            this.Invoke(new EventHandler(delegate
            {
                lainfo.Text = datastr;

                switch (PinBoardRWStatus)
                {
                    case ReadWriteStatus.ReadIDAck:
                        PinBoardRWStatus = ReadWriteStatus.Free;
                        //if (datastr.Contains("RID"))
                        if(datastr.Length > 0)
                        {
                            MessageBox.Show("读ID成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
                        }
                        else
                        {
                            MessageBox.Show("通讯失败，请检查端口选择是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        
                        break;
                    case ReadWriteStatus.WriteIDAck:
                        PinBoardRWStatus = ReadWriteStatus.Free;
                        string resultstr = "WID_" + tbPinBoardID.Text.Trim();
                        if (datastr.Contains(resultstr))
                        {
                            MessageBox.Show("ID设置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
                            if( cb_AutoRead.Checked == true)
                            {
                                this.Invoke(new EventHandler(delegate
                                {
                                    buttonCtl(true);
                                    button2.PerformClick();
                                    
                                }));
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("ID设置失败，请检查端口选择是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        
                        break;
                    default:

                        break;
                }

                buttonCtl(true);
        }));
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            Thread th = threadMana["ReadThread"];

            try {
                th.Abort();
                threadMana.Remove("ReadThread");
            }
            catch { }

            if((PinBoardRWStatus == ReadWriteStatus.ReadIDAck) 
                || (PinBoardRWStatus == ReadWriteStatus.WriteIDAck))
            {
                MessageBox.Show("通讯失败，如果软件无响应，请重新打开软件，重新给箱子上电！", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
            }

            ////serialPort1.ReadTimeout = 1000;
            ////string datastr = serialPort1.ReadLine();
            ////char[] cdata = new char[1024];
            ////serialPort1.Read(cdata, 0, 1024);
            ////string datastr = cdata.ToString();
            //this.Invoke(new EventHandler(delegate
            //{
            //    string datastr = serialPort1.ReadLine();

            //    lainfo.Text = datastr;


            //    switch (PinBoardRWStatus)
            //    {
            //        case ReadWriteStatus.ReadIDAck:

            //            if (datastr.Contains("RID"))
            //            {
            //                MessageBox.Show("通讯成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
            //            }
            //            else
            //            {
            //                MessageBox.Show("通讯失败，请检查端口选择是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //            }
            //            PinBoardRWStatus = ReadWriteStatus.Free;
            //            break;
            //        case ReadWriteStatus.WriteIDAck:
            //            string resultstr = "WID_" + tbPinBoardID.Text.Trim();
            //            if(datastr.Contains(resultstr))
            //            {
            //                MessageBox.Show("ID设置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
            //            }
            //            else
            //            {
            //                MessageBox.Show("ID设置失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //            }
            //            PinBoardRWStatus = ReadWriteStatus.Free;
            //            break;
            //        default:

            //            break;
            //    }

            //    buttonCtl(true);
            //}));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                try
                {
                    serialPort1.Close();
                }
                catch
                {
                }
            }
        }

        private void tb_Bauds_TextChanged(object sender, EventArgs e)
        {
            if (tb_Bauds.Text == "") return;
            label2.Text = "提示：软件当前串口波特率为" + tb_Bauds.Text.Trim();
            //label2.Text = "提示：软件当前串口波特率为" + serialPort1.BaudRate.ToString();
        }
    }
}
